package springboot.utlis;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传下载工具类
 * 
 * @author lixu
 *
 */
public class FileUtils {
	/**
	 * 文件上传
	 * 
	 * @throws IOException
	 * @throws IllegalStateException
	 */
	public static Map<String, Object> UpLoadFile(MultipartFile mFile, String mFilePath, Map<String, Object> map)
			throws IllegalStateException, IOException {
		// 返回上传的文件是否为空，即没有选择任何文件，或者所选文件没有内容。
		// 防止上传空文件导致奔溃
		if (mFile.isEmpty()) {
			map.put("message", "文件为空");
			return map;
		}
		/**
		 * 获取文件名称 getName : 获取表单中文件组件的名字 getOriginalFilename : 获取上传文件的原名
		 */
		String fileName = mFile.getOriginalFilename();
		// 默认路径
		if (mFilePath == null || mFilePath.isEmpty()) {
			mFilePath = "C:\\Users\\lixu\\Downloads";
		}
		// 设置文件保存的路径
		String filePath = mFilePath;
		// 创建文件保存路径
		File dest = new File(filePath + fileName);
		// 检测是否存在该目录
		if (!dest.getParentFile().exists()) {
			// 不存在就创建
			dest.getParentFile().mkdirs();
		}
		mFile.transferTo(dest);
		map.put("filePath", filePath + fileName);
		return map;
	}

	/**
	 * 文件下载
	 * 
	 * @throws IOException
	 */
	public static void downloadFile(HttpServletResponse res, String mFileName) throws IOException {
		res.setHeader("content-type", "application/octet-stream");
		res.setContentType("application/octet-stream");
		res.setHeader("Content-Disposition", "attachment;filename=" + mFileName);
		byte[] buff = new byte[1024];
		BufferedInputStream bis = null;
		OutputStream os = null;
		os = res.getOutputStream();
		bis = new BufferedInputStream(new FileInputStream(
				new File("D:/EclipseProject/springboot/src/main/resources/static/upload/" + mFileName)));
		int i = bis.read(buff);
		while (i != -1) {
			os.write(buff, 0, buff.length);
			os.flush();
			i = bis.read(buff);
			if (bis != null) {
				bis.close();
			}
		}
	}
}
